// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dfa.axis.v1_19.matchtables;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

/**
 * Utility class to print infinite progress in a separate thread.  To be used during long Remote
 * lookups.
 *
 * @author Moshe Kahan
 */
public class Spinner implements Callable<Void> {
  private static final int SPIN_INTERVAL = 100;
  private volatile boolean spin;
  private ExecutorService executor;
  private Future<?> future;

  Spinner() {
    spin = false;
    // Set up executor.
    executor = Executors.newSingleThreadExecutor(
        new ThreadFactory() {
          public Thread newThread(Runnable runnable) {
            Thread thread = Executors.defaultThreadFactory().newThread(runnable);
            thread.setDaemon(true);
            return thread;
          }
        }); 
  }

  public void spin() {
    spin = true;
    future = executor.submit(this);
  }

  public void stop() {
    spin = false;
    try {
      future.get();
    } catch (Exception e) {
      // snooze
    }
  }

  public Void call() {
    int i = 0;
    while (spin) {
      System.out.print("\r                    \r");
      for (int j = 0; j < (i++ % 16) && spin; ++j) {
        System.out.print("*");
        try {
          Thread.sleep(SPIN_INTERVAL);
        } catch (InterruptedException e) {
          return null;
        }
      }
    }
    return null;
  }
}
